package net.dl.ss.web;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.dl.ss.dao.CategoryDao;
import net.dl.ss.domain.Category;
import net.dl.ss.service.ContextManager;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

/**
 * @author yakovlev.yuriy@gmail.com
 * @since 12.8.2008
 */
@Controller
public class CategoriesController extends BaseController {
	protected final Log logger = LogFactory.getLog(getClass());
	private final CategoryDao categoryDao;

	@Autowired
	public CategoriesController(CategoryDao categoryDao) {
		this.categoryDao = categoryDao;
	}
	
	@RequestMapping("/categoriesList.htm")
	protected void eventsListHandler(HttpServletRequest request, HttpServletResponse response) {
		try {
			ServletOutputStream  os = response.getOutputStream();
			modifyResponseHeader(response, "text/xml");
			
		    os.println("<categories>");
		    Long eventId = ContextManager.getCurrentEvent(request);
		    if(eventId!=null) {
		    	List<Category> categories = this.categoryDao.findByEventId(eventId);
				for(Category category : categories) {
			    	os.print(category.toXML());
			    }
		    }
		    os.println("</categories>");
	
			os.close();
		} catch (IOException e) {
			logger.error(e.getMessage());
		} 
	}

	@RequestMapping("/categoryUpdate.htm")
	public void eventUpdateHandler(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		ServletOutputStream  os = response.getOutputStream();
		modifyResponseHeader(response, "text/plain");
		
		Long eventId = ContextManager.getCurrentEvent(request);
	    if(eventId!=null) {
		    Category cat = new Category();
		    cat.setEventId(eventId);
			cat.setName(request.getParameter("name"));
			try {
				String id = request.getParameter("id");
				if(id!=null && !"".equals(id)) {
					cat.setId(Long.parseLong(id));
					this.categoryDao.updateEntity(cat);
				} else {
					this.categoryDao.saveEntity(cat);
				}
				os.print("{success:true}");
			} catch(Exception ex) {
				logger.error(ex.getMessage());
			}
	    } else {
			os.print("{success:false}");
	    }
	    os.close();
	}

}
